<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no" />
    <title>沟通中</title>
    <link rel="stylesheet" type="text/css" href="__STATIC__/mychat/css/themes.css?v=2017129">
    <link rel="stylesheet" type="text/css" href="__STATIC__/mychat/css/h5app.css">
    <link rel="stylesheet" type="text/css" href="__STATIC__/mychat/fonts/iconfont.css?v=2016070717">
    <!--JS版本不能大于1.9否则qqFace插件会出现msie报错，1.9之后版本的js移除了msie-->
    <script src="__STATIC__/mychat/js/jquery.min2.js"></script>
    <script src="__STATIC__/mychat/js/dist/flexible/flexible_css.debug.js"></script>
    <script src="__STATIC__/mychat/js/dist/flexible/flexible.debug.js"></script>
    <script src="__STATIC__/qqFace/js/jquery.qqFace.js"></script>
    <style>
        .qqFace { margin-top: -180px; background: #fff; padding: 2px; border: 1px #dfe6f6 solid; }
        .qqFace table td { padding: 0px; }
        .qqFace table td img { cursor: pointer; border: 1px #fff solid; }
        .qqFace table td img:hover { border: 1px #0066cc solid; }
    </style>
</head>
<body ontouchstart>
<div class='fui-page-group'>
<div class='fui-page chatDetail-page'>
    <div class="chat-header flex">
        <i class="icon icon-toleft t-48"></i>
        <span class="shop-titlte t-30" id="title">测试</span>
        <span class="shop-online t-26"></span>
        <span class="into-shop">进店</span>
    </div>
    <div class="fui-content navbar" style="padding:1.2rem 0 1.35rem 0;">
        <div class="chat-content">
            <p style="display: none;text-align: center;padding-top: 0.5rem" id="more"><a>加载更多</a></p>
            <p class="chat-time"><span class="time">2017-11-12</span></p>

            <!--<div class="chat-text section-left flex">-->
            <!--<span class="char-img img1"></span>-->
            <!--<span class="text"><i class="icon icon-sanjiao4 t-32"></i>你好</span>-->
            <!--</div>-->

            <!--<div class="chat-text section-right flex">-->
            <!--<span class="text"><i class="icon icon-sanjiao3 t-32"></i>你好</span>-->
            <!--<span class="char-img img2"></span>-->
           <!--</div>-->
        </div>
    </div>
    <div class="fix-send flex footer-bar">
        <i class="icon icon-emoji1 t-50"></i>
        <input class="send-input t-28" maxlength="200" id="saytext">
        <input type="file" name="pic" id="file" style="display: none;">
        <i class="icon icon-add image_up t-50" style="color: #888;"></i>
        <span class="send-btn">发送</span>
    </div>
</div>
</div>
<script>
    var from_id = {$from_id};
    var to_id = {$to_id};
    var from_head = '';
    var to_head = '';
    var to_name = '未知用户';
    var online = 1;//在线
    //链接socket
    var ws = new WebSocket("ws://127.0.0.1:8282");
    //接收socket发送的消息
    ws.onmessage = function (e) {
        //处理接收到的消息
        var msg = JSON.parse(e.data);
        switch (msg.type){
            case 'init':
                var bind = '{"type":"bind","from_id":"'+from_id+'"}';
                //绑定聊天对象
                ws.send(bind);
                //获取双方头像
                get_head(from_id,to_id);
                //获取聊天对象
                get_name(to_id);
                //加载聊天对象
                msg_load();
                //判断在线
                is_online();
                //消息已读
                readMsg();
                return;
            //接收消息
            case 'text':
                if (to_id == msg.from_id) {
                    msg.data = replace_em(msg.data);
                    receive_div(msg.data);
                }
                //消息已读
                setTimeout("readMsg()",500);
                return;
            //消息持久化
            case 'save':
                save_msg(msg);
                if (msg.isread == 1){
                    online = 1;
                    $(".shop-online").text('在线');
                }else{
                    online = 0;
                    $(".shop-online").text('离线');
                }
                return;
            //接收图片消息
            case 'say_img':
                if (to_id == msg.from_id) {
                    var str = '<img src="__ROOT__/uploads/'+msg.img_name+'" width="120em" height="120em">';
                    receive_div(str);
                }
                //消息已读
                setTimeout("readMsg()",500);
                return;
            //在线判断
            case 'online':
                if (msg.status == 1){
                    online = 1;
                    $(".shop-online").text('在线');
                }else{
                    online = 0;
                    $(".shop-online").text('离线');
                }
                return;
        }
    };
    //发送消息到服务器
    $(".send-btn").click(function () {
        var text = $(".send-input").val();
        var msg = '{"data":"'+text+'","type":"say","from_id":'+from_id+',"to_id":'+to_id+'}';
        ws.send(msg);
        //拼接聊天数据
        send_div(replace_em(text));
        $(".send-input").val('');
    });
    //消息持久化（单用户多窗口不同接收方cors不同源可能出现多次插入数据，后期需要处理）
    function save_msg(msg) {
        $.post('/index.php/api/mychat/saveMsg',msg,function (e) {},'json');
    }
    //获取头像
    function get_head(from_id,to_id) {
        $.post('/index.php/api/mychat/getHead',{from_id:from_id,to_id:to_id},function (e) {
            from_head = e.from_head;
            to_head = e.to_head;
        },'json');
    }
    //获取昵称
    function get_name(to_id) {
        $.post('/index.php/api/mychat/getName/uid/'+to_id,'',function (e) {
            if (e.length>0){
                to_name = e;
            }
            $("#title").text('与'+to_name+'聊天中...')
        },'json');
    }
    //获取聊天记录
    function msg_load(){
        $.post('/index.php/api/mychat/loadMsg',{from_id:from_id,to_id:to_id},function (e) {
            $.each(e,function (i,item) {
                if(from_id == item.fromid){
                    //拼接聊天数据
                    //图片类型
                    if (item.type == 2){
                        item.content = '<img src="__ROOT__/uploads/'+item.content+'" width="120em" height="120em">';
                    }else{
                        //替换表情
                        item.content = replace_em(item.content)
                    }
                    send_div(item.content);
                }else{
                    if (item.type == 2){
                        item.content = '<img src="__ROOT__/uploads/'+item.content+'" width="120em" height="120em">';
                    }else{
                        //替换表情
                        item.content = replace_em(item.content)
                    }
                    receive_div(item.content);
                }
            });
        },'json');
    }
    //判断在线
    function is_online() {
        var online = '{"type":"online","to_id":"'+to_id+'","from_id":"'+from_id+'"}';
        ws.send(online);
    }
    //拼接发送方聊天记录
    function send_div(msg) {
        $(".chat-content").append('<div class="chat-text section-right flex">'
            +'<span class="text"><i class="icon icon-sanjiao3 t-32"></i>' + msg + '</span>'
            +'<span class="char-img img2" style="background-image: url('+from_head+')"></span></div>');
        $(".chat-content").scrollTop(3000);
    }
    //拼接接收方聊天记录
    function receive_div(msg) {
        $(".chat-content").append(' <div class="chat-text section-left flex">'
            +'<span class="char-img img1" style="background-image: url('+to_head+')"></span>'
            +'<span class="text"><i class="icon icon-sanjiao4 t-32"></i>' + msg + '</span></div>');
        $(".chat-content").scrollTop(3000);
    }
    //点击图片
    $(".image_up").click(function () {
        $("#file").click();
    });
    //异步上传图片
    $("#file").change(function () {
        var formdata = new FormData();
        //追加数据
        formdata.append('from_id',from_id);
        formdata.append('to_id',to_id);
        formdata.append('online',online);
        formdata.append('file',$("#file")[0].files[0]);
        $.ajax({
            url:'/index.php/api/mychat/uploadImg',
            type:'post',
            //禁止读取缓存
            cache:false,
            data:formdata,
            dateType:'json',
            //去除默认数据格式，在上传文件时就不会报错
            contentType:false,
            //默认所有内容转为对象形式(禁止掉)
            processData:false,
            success:function (data,status) {
                if (data.status == 'ok'){
                    var str = '<img src="__ROOT__/uploads/'+data.img_name+'" width="120em" height="120em">';
                    send_div(str);
                    var msg = '{"data":"'+data.img_name+'","from_id":"'+from_id+'","to_id":"'+to_id+'","type":"say_img"}';
                    ws.send(msg);
                }else{
                    console.log(data.status);
                }
            }
        });
    });

    //标记消息已读
    function readMsg(){
        $.post(
            '/index.php/api/mychat/readMsg',
            {"from_id":from_id,"to_id":to_id},
            function () {},'json')
    }

    //qq表情
    $(function(){
        $('.icon-emoji1').qqFace({
            id : 'facebox',
            assign:'saytext', //输入文本框
            path:'__STATIC__/qqFace/arclist/'	//表情存放的路径
        });
    });

    //替换表情
    function replace_em(str){
        str = str.replace(/\</g,'&lt;');
        str = str.replace(/\>/g,'&gt;');
        str = str.replace(/\n/g,'<br/>');
        str = str.replace(/\[em_([0-9]*)\]/g,'<img src="__STATIC__/qqFace/arclist/$1.gif" border="0" />');
        return str;
    }
</script>
</body>
</html>
